package com.hyj.dev.tess4j;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;

import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.gui.util.HorizontalPanel;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.log4j.Logger;

/**
 * @author hyj
 * 
 */
public class MainPanel {

	private static final Logger log = Logger.getLogger(MainPanel.class);

	private static MainPanel panel;

	public synchronized static MainPanel getInstance() {
		if (panel == null) {
			panel = new MainPanel();
		}
		return panel;
	}

	private JPanel dataPanel;

	private MainPanel() {
		log.info("创建验证码识别插件面板");
		init();
	}

	private void init() {
		JPanel settingPanel = new VerticalPanel(5, 0);

		// 添加输入panel到主panel
		settingPanel.add(getLanguagePathPanel());
		settingPanel.add(getLanguagePanel());
		settingPanel.add(getCaptchaTypePanel());
		settingPanel.add(getInputPanel());
		settingPanel.add(getOutPutPanel());
		settingPanel.add(getInfoPanel());

		// 设置主panel参数
		dataPanel = new JPanel(new BorderLayout(5, 0));
		dataPanel.add(settingPanel, BorderLayout.NORTH);
	}

	private JTextField languagePathText;
	private JComboBox<String> language;
	private JComboBox<CaptchaType> cmb;
	private JTextField inputText;
	private JTextField outputText;

	private JTextArea outInfo;

	/**
	 * 为每组输入框封装为panel
	 * 
	 * @param label
	 * @return
	 */
	private JPanel getIitemPanel(JLabel label) {
		Component component = label.getLabelFor();

		JPanel panel = new HorizontalPanel();
		panel.add(label, BorderLayout.WEST);
		panel.add(component, BorderLayout.CENTER);
		return panel;
	}

	/**
	 * 创建语言包输入panel
	 * 
	 * @return
	 */
	private JPanel getLanguagePathPanel() {
		languagePathText = new JTextField();
		languagePathText.setToolTipText("为空/默认查找 {JMEMTER_HOME}/lib/tessdata, {JMEMTER_HOME}/lib/ext/tessdata");

		// 添加失去焦点验证
		languagePathText.addFocusListener(new FocusListener() {
			@Override
			public void focusGained(FocusEvent e) {
			}

			@Override
			public void focusLost(FocusEvent e) {
				buildLanguage();
			}
		});

		JLabel label = new JLabel("语言包路径：");
		label.setLabelFor(languagePathText);

		return getIitemPanel(label);
	}

	/**
	 * 加载语言包
	 */
	private void buildLanguage() {
		Object selectedItem = language.getSelectedItem();
		// 执行验证语言包路径并设置语言
		String languagePath = getLanguagePath();
		log.debug("语言包路径设置为：" + languagePath);
		File file = new File(languagePath);
		File[] files = file.listFiles((File item) -> {
			return item.isFile() && item.getPath().endsWith(".traineddata");
		});
		language.removeAllItems();
		if (files == null || files.length == 0) {
			String info = "【验证码识别插件】  语言包路径[" + languagePath + "] 下没有找到任何语言包！";
			printInfo(info);
			return;
		}
		for (File item : files) {
			String name = item.getName();
			language.addItem(name.substring(0, name.indexOf(".")));
		}
		if (selectedItem == null) {
			language.setSelectedIndex(0); // 默认选中第一个
		} else {
			language.setSelectedItem(selectedItem);
		}
	}

	/**
	 * 创建语言选项
	 * 
	 * @return
	 */
	private JPanel getLanguagePanel() {
		language = new JComboBox<>();
		buildLanguage();

		JLabel label = new JLabel("使用语言包：");
		label.setLabelFor(language);

		return getIitemPanel(label);
	}

	/**
	 * 创建类型选择器panel
	 * 
	 * @return
	 */
	private JPanel getCaptchaTypePanel() {
		cmb = new JComboBox<>();
		cmb.addItem(CaptchaType.Base64);
		cmb.addItem(CaptchaType.文件流);

		JLabel label = new JLabel("验证码类型：");
		label.setLabelFor(cmb);

		return getIitemPanel(label);
	}

	/**
	 * 创建输入变量panel
	 * 
	 * @return
	 */
	private JPanel getInputPanel() {
		inputText = new JTextField("captcha");
		JLabel label = new JLabel("输入变量：");
		label.setLabelFor(inputText);

		return getIitemPanel(label);
	}

	/**
	 * 创建输出变量panel
	 * 
	 * @return
	 */
	private JPanel getOutPutPanel() {
		outputText = new JTextField("captcha");
		JLabel label = new JLabel("输出变量：");
		label.setLabelFor(outputText);

		return getIitemPanel(label);
	}

	private static final Border BLACK_BORDER = BorderFactory.createLineBorder(Color.BLACK);
	private static final Border RED_BORDER = BorderFactory.createLineBorder(Color.RED);

	public JPanel getInfoPanel() {
		outInfo = new JTextArea(20, 20);
		outInfo.setEditable(false);
		outInfo.addFocusListener(new FocusListener() {
			@Override
			public void focusGained(FocusEvent e) {
				outInfo.setBorder(BLACK_BORDER);
			}
			public void focusLost(FocusEvent e) {}
		});
		
		
		JScrollPane scrollPane = new JScrollPane(outInfo);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

		JPanel panel = new HorizontalPanel();
		panel.add(scrollPane);
		return panel;
	}

	public JPanel getPanel() {
		return this.dataPanel;
	}
	
	
	public void printInfo(String info) {
		if(outInfo != null) {
			outInfo.setBorder(RED_BORDER);
			outInfo.setText(info);
		}
	}

	public String getLanguagePath() {
		String text = languagePathText.getText();
		if (StringUtils.isEmpty(text)) {
			String jMeterHome = JMeterUtils.getJMeterHome();
			File file = new File(jMeterHome, "/lib/tessdata");
			if (!file.exists() && !file.isDirectory()) {
				file = new File(jMeterHome, "/lib/ext/tessdata");
			}
			if (!file.exists() && !file.isDirectory()) {
				log.warn("找不到语言包。请配置语言包路径，或将语言包（tessdata）文件夹放在{JMEMTER_HOME}/lib/tessdata, {JMEMTER_HOME}/lib/ext/tessdata 下");
			} else {
				text = file.getAbsolutePath();
			}
		}
		return text;
	}

	public void setLanguagePath(String languagePath) {
		languagePathText.setText(languagePath);
	}

	public String getLanguage() {
		return (String) language.getSelectedItem();
	}

	public void setLanguage(String lan) {
		buildLanguage();
		language.setSelectedItem(lan);
	}

	public CaptchaType getCaptchaType() {
		return (CaptchaType) cmb.getSelectedItem();
	}

	public String getCaptchaTypeStr() {
		return ((CaptchaType) cmb.getSelectedItem()).name();
	}

	public void setCaptchaType(CaptchaType type) {
		if (type == null) {
			type = CaptchaType.Base64;
		}
		cmb.setSelectedItem(type);
	}

	public void setCaptchaType(String type) {
		CaptchaType val;
		try {
			val = CaptchaType.valueOf(type);

		} catch (Exception e) {
			val = CaptchaType.Base64;
		}
		setCaptchaType(val);
	}

	/**
	 * 获取input
	 * 
	 * @return
	 */
	public String getInputText() {
		return inputText.getText();
	}

	public void setInputText(String text) {
		if (StringUtils.isEmpty(text)) {
			text = "captcha";
		}
		inputText.setText(text);
	}

	/**
	 * 获取output
	 * 
	 * @return
	 */
	public String getOnputText() {
		return outputText.getText();
	}

	/**
	 * 设置output
	 * 
	 * @param text
	 */
	public void setOutputText(String text) {
		if (StringUtils.isEmpty(text)) {
			text = "captcha";
		}
		outputText.setText(text);
	}

	/**
	 * 重置
	 */
	public void reset() {
		setLanguagePath(null);
		setLanguage(null);
		setCaptchaType(CaptchaType.Base64);
		setInputText("captcha");
		setOutputText("captcha");
	}

}
